package top.fengyulou.xiaofeng.service;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import top.fengyulou.xiaofeng.common.UserUtils;
import top.fengyulou.xiaofeng.dto.UserDto;
import top.fengyulou.xiaofeng.mapper.UserMapper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class LoginService {

    private static final Logger LOG = LoggerFactory.getLogger(LoginService.class);

    @Resource
    private UserMapper userMapper;

    //用户登录
    public boolean login(String loginName, String password, String type, HttpServletRequest request) {
        UserDto query = new UserDto();
        query.setLoginName(loginName);
        query.setType(type);
        UserDto userDto = userMapper.getByLoginNameAndType(query);
        if (userDto == null) {
            LOG.info("用户不存在，{}", query.getLoginName());
            return false;
        } else {
            if (userDto.getPassword().equals(password)) {
                //登录成功，存放数据
                if (StringUtils.isBlank(userDto.getName())) {
                    userDto.setShowName(userDto.getLoginName());
                } else {
                    userDto.setShowName(userDto.getName());
                }
                userDto.setPassword("");
                UserUtils.login(request, userDto);
            } else {
                LOG.info("密码错误，{}:{}", loginName, password);
                return false;
            }
        }
        return true;
    }
}
